package com.landmark;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Scanner;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

public class RenameImageNames extends JPanel {

    public void start() throws Exception {
        HelperBean helperBean = Util.getHelperBean();
        //BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String imageFolderPath = helperBean.getFolderPath(); // images folder
        String nameFilePath = helperBean.getFilePath(); // colorcode file
        String imagePrefix = helperBean.getPrefix();
        String imageSuffix = helperBean.getSuffix();

        String convertedImagesFolder = "./output/ConvertedImages/";
        String nonConvertedImages = "./output/NonConvertedImages/";

        Util.createDirectory(convertedImagesFolder);
        Util.createDirectory(nonConvertedImages);
        Util.createOutputFile("RenameImages");
        fw = new FileWriter(Util.getHelperBean().getOutputFile());
        System.out.println(Util.getHelperBean().getOutputFile().getAbsolutePath());
        fwErrorFile = new FileWriter(Util.getHelperBean().getErrorFile());
        // get the names into hashtable
        processFile(new File(nameFilePath));

        String[] dir = new java.io.File(imageFolderPath).list();
        java.util.Arrays.sort(dir);
        File f[] = new File(imageFolderPath).listFiles();

        int len1 = dir.length;
        File inputFile = new File(nameFilePath);
        if (inputFile.exists()) {
            BufferedReader bf = new BufferedReader(new FileReader(inputFile));
            String line = "";
            while ((line = bf.readLine()) != null) {
                String imageName = line;
                performRename(f, len1, imageName, imagePrefix, imageSuffix, convertedImagesFolder);
            }
        }
    }

    /***
     * This will rename all the images in the folder with the names present 
     * in the file and will give an output file with the names that have not been 
     * renamed from the file.
     * The images are shifted to other location from the main location where the 
     * image path is specified.
     * @param f
     * @param len1
     * @param imageName
     * @param imagePrefix
     * @param imageSuffix
     * @param convertedImagesFolder
     * @throws Exception 
     */
    private void performRename(File[] f, int len1, String imageName, String imagePrefix, String imageSuffix, String convertedImagesFolder) throws Exception {
        boolean found = false;
        for (int i = 0; i < len1; i++) {
            String name = f[i].getName();
            String imageFileName = name.substring(0, name.lastIndexOf("."));
            if (imageFileName.equalsIgnoreCase(imageName)) {
                String replaceWith = imageName;
                System.out.println(":" + imageFileName);
                replaceWith = imagePrefix + "_" + replaceWith + "_" + imageSuffix + name.substring(name.lastIndexOf("."), name.length());
                File newFileName = new File(convertedImagesFolder + replaceWith);
                boolean stat = f[i].renameTo(newFileName);
                found = true;
                break;
            }
        }
        if (!found) {
            fw.write(imageName+"\n");
            fw.flush();
        }
    }

    public void start_old() {
        HelperBean helperBean = Util.getHelperBean();
        //BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String imageFolderPath = helperBean.getFolderPath(); // images folder
        String nameFilePath = helperBean.getFilePath(); // colorcode file
        String imagePrefix = helperBean.getPrefix();
        String imageSuffix = helperBean.getSuffix();

        String convertedImagesFolder = "./output/ConvertedImages/";
        String nonConvertedImages = "./output/NonConvertedImages/";
        try {

            Util.createDirectory(convertedImagesFolder);
            Util.createDirectory(nonConvertedImages);
            Util.createOutputFile("RenameImages");
            fw = new FileWriter(Util.getHelperBean().getOutputFile());
            fwErrorFile = new FileWriter(Util.getHelperBean().getErrorFile());
            // get the names into hashtable
            processFile(new File(nameFilePath));
        } catch (Exception e) {
            e.printStackTrace();
            try {
                fw.append(e.getMessage());
                fw.flush();
            } catch (Exception e1) {
            }
        }

        String[] dir = new java.io.File(imageFolderPath).list();
        java.util.Arrays.sort(dir);
        File f[] = new File(imageFolderPath).listFiles();

        int len1 = dir.length;
        System.out.println(htColorCodes.size());
        int thumbNailCount = 0;
        for (int i = 0; i < len1; i++) {
            String name = f[i].getName();
            //System.out.println("FileName:"+name);
            String imageFileName = name.substring(0, name.lastIndexOf("."));
            String replaceWith = getValue(imageFileName.trim());
            System.out.println(":" + imageFileName);
            try {
                if (replaceWith != null && !"".equalsIgnoreCase(replaceWith)) {
                    replaceWith = imagePrefix + "_" + replaceWith + "_" + imageSuffix + name.substring(name.lastIndexOf("."), name.length());
                    //File newFileName = new File(f[i].getParentFile(), replaceWith);
                    File newFileName = new File(convertedImagesFolder + replaceWith);
                    boolean stat = f[i].renameTo(newFileName);
                    System.out.println("Moooved:" + stat);

                }
//                else {
//                    fw.append("\n" + f[i].getName());
//                    fw.flush();
//                    File file = new File(nonConvertedImages + f[i].getName());
//                    System.out.println(file.getAbsolutePath());
//                    boolean stat = f[i].renameTo(file);
//                    System.out.println("MOved : " + stat);
//                }
            } catch (Exception e) {
                e.printStackTrace();
                JOptionPane.showMessageDialog(this, e.getCause());
            }
        }
        System.out.println("Total files converted : " + (len1 - thumbNailCount));
    }

    /**
     * *
     * This method is used to get the names of images from the file and store
     * them in a Hashtable for later use
     *
     * @param inputFile
     * @throws Exception
     */
    private void processFile(File inputFile) throws Exception {
        htColorCodes = new Hashtable<String, String>();
        if (inputFile.exists()) {
            Scanner inputScan = new Scanner(inputFile);
            while (inputScan.hasNext()) {
                String imageName = inputScan.nextLine();
                htColorCodes.put(imageName.trim(), imageName.trim());
            }
        }
    }

    private String getValue(String aKey) {
        Enumeration<String> keys = htColorCodes.keys();
        String value = "";
        while (keys.hasMoreElements()) {
            String key = keys.nextElement();
            if (key.equalsIgnoreCase(aKey)) {
                value = htColorCodes.get(key);
                break;
            }
        }
        System.out.println(":" + aKey + " ---:" + value);
        return value;
    }
    Hashtable<String, String> htColorCodes;
    FileWriter fw = null;
    FileWriter fwErrorFile = null;
}
